#![windows_subsystem = "windows"]
mod cmd;
mod excel;
use rust_xlsxwriter::XlsxError;
use clipboard::ClipboardContext;
use clipboard::ClipboardProvider;
use druid::kurbo::Line;
use druid::piet::{RenderContext,FontFamily};
use druid::widget::{
    prelude::*, Align, Button, Controller, CrossAxisAlignment, Either, EnvScope, Flex, Label,
    MainAxisAlignment, Painter, Split, TextBox, ViewSwitcher,
};
use druid::{
    commands, theme, AppDelegate, AppLauncher, Color, Command, Data, DelegateCtx,//LinearGradient,
    FileDialogOptions, FileSpec, Handled, Lens, Menu, MenuItem, Point, Target, UnitPoint,
    WidgetExt, WindowDesc, WindowState,TextLayout,FontDescriptor,
};
use libloader::libloading;
use std::sync::OnceLock;
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::time::Instant;
use windows_sys::Win32::Foundation::{HWND, MAX_PATH};
use windows_sys::Win32::UI::Controls::Dialogs::{
    GetOpenFileNameW, OFN_ALLOWMULTISELECT, OFN_EXPLORER, OPENFILENAMEW,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
    FindWindowW, MessageBoxW, SetForegroundWindow, ShowWindow, MB_ICONINFORMATION, MB_OK,
    SW_RESTORE,GetSystemMetrics, SM_CXSCREEN, //SM_CYSCREEN,
};
static SCREEN_WIDTH: OnceLock<f64> = OnceLock::new();
//static SCREEN_HEIGHT: OnceLock<f64> = OnceLock::new();
fn get_screen_width() -> f64 {
    *SCREEN_WIDTH.get_or_init(|| unsafe { GetSystemMetrics(SM_CXSCREEN).into() })
}
// fn get_screen_height() -> f64 {
//     *SCREEN_HEIGHT.get_or_init(|| unsafe { GetSystemMetrics(SM_CYSCREEN).into() })
// }
#[derive(Clone, Data, Lens)]
struct AppState {
    display: String,
    show_hide: bool,
    current_view: u8,
    sidebar_view: u8,
    max_res_icon:String,
    folder_path:String,
    #[data(eq)]
    data: Vec<f64>,
}
struct Delegate;
struct Windowstate;
struct SwitchViews;
struct DragController;
struct MainMenuController;
struct MessageBoxTextController;
struct MessageBoxFocusController;
struct FolderIconColorController;
struct DocumentIconColorController;

impl<W: Widget<AppState>> Controller<AppState, W> for Windowstate {
    fn event(
        &mut self,
        child: &mut W,
        ctx: &mut EventCtx,
        event: &Event,
        data: &mut AppState,
        env: &Env,
    ) {
        if ctx.window().get_window_state() == WindowState::Maximized{
            data.max_res_icon = "﹃﹄".to_string();
        }
        else{
            data.max_res_icon = "▢".to_string();
        }
        child.event(ctx, event, data, env)
    }
}

impl Controller<AppState, Label<AppState>> for SwitchViews {
    fn update(
        &mut self,
        child: &mut Label<AppState>,
        ctx: &mut UpdateCtx,
        old_data: &AppState,
        data: &AppState,
        env: &Env,
    ) {
        if data.current_view == 0 {
            child.set_text("NEXT🔜");
            ctx.request_layout();
        } else {
            child.set_text("🔙PREVIOUS");
            ctx.request_layout();
        }
        child.update(ctx, old_data, data, env);
    }
}
impl<W: Widget<AppState>> Controller<AppState, W> for DragController {
    fn event(
        &mut self,
        child: &mut W,
        ctx: &mut EventCtx,
        event: &Event,
        data: &mut AppState,
        env: &Env,
    ) {
        if let Event::MouseMove(_) = event {ctx.window().handle_titlebar(true);}
        child.event(ctx, event, data, env)
    }
}
impl<W: Widget<AppState>> Controller<AppState, W> for MainMenuController {
    fn event(
        &mut self,
        child: &mut W,
        ctx: &mut druid::EventCtx,
        event: &druid::Event,
        data: &mut AppState,
        env: &druid::Env,
    ) {
        if let Event::MouseDown(e) = event {
            if e.button.is_left() && ctx.is_hot() {
                ctx.show_context_menu(make_main_menu(), Point::new(36., 28.));
            }
        }
        child.event(ctx, event, data, env)
    }
}
impl<W: Widget<AppState>> Controller<AppState, W> for MessageBoxTextController {
    fn event(
        &mut self,
        child: &mut W,
        ctx: &mut druid::EventCtx,
        event: &druid::Event,
        data: &mut AppState,
        env: &druid::Env,
    ) {
        if let Event::MouseDown(e) = event {
            if e.button == druid::MouseButton::Left {
                data.display = String::from(">>正在爬取沪深京A股数据请稍后->->->");
            }
        }
        child.event(ctx, event, data, env)
    }
}
impl<W: Widget<AppState>> Controller<AppState, W> for MessageBoxFocusController {
    fn event(
        &mut self,
        child: &mut W,
        ctx: &mut druid::EventCtx,
        event: &druid::Event,
        data: &mut AppState,
        env: &druid::Env,
    ) {
        if let Event::MouseDown(e) = event {
            if e.button == druid::MouseButton::Left {
                ctx.request_focus();
            }
        }
        child.event(ctx, event, data, env)
    }
}
impl Controller<AppState, Label<AppState>> for FolderIconColorController {
    fn event(
        &mut self,
        child: &mut Label<AppState>,
        ctx: &mut druid::EventCtx,
        event: &druid::Event,
        data: &mut AppState,
        env: &druid::Env,
    ) {
        if ctx.is_hot() || (data.show_hide == true && data.sidebar_view == 0) {
            child.set_text_color(Color::WHITE);
            ctx.request_layout();
        } else {
            child.set_text_color(Color::rgb8(170, 170, 170));
            ctx.request_layout();
        }
        child.event(ctx, event, data, env)
    }
    fn update(
        &mut self,
        child: &mut Label<AppState>,
        ctx: &mut UpdateCtx,
        old_data: &AppState,
        data: &AppState,
        env: &Env,
    ) {
        if data.show_hide == true && data.sidebar_view == 0 {
            child.set_text_color(Color::WHITE);
            ctx.request_layout();
        } else {
            child.set_text_color(Color::rgb8(170, 170, 170));
            ctx.request_layout();
        }
        child.update(ctx, old_data, data, env);
    }
}
impl Controller<AppState, Label<AppState>> for DocumentIconColorController {
    fn event(
        &mut self,
        child: &mut Label<AppState>,
        ctx: &mut druid::EventCtx,
        event: &druid::Event,
        data: &mut AppState,
        env: &druid::Env,
    ) {
        if ctx.is_hot() || (data.show_hide == true && data.sidebar_view == 1) {
            child.set_text_color(Color::WHITE);
            ctx.request_layout();
        } else {
            child.set_text_color(Color::rgb8(170, 170, 170));
            ctx.request_layout();
        }
        child.event(ctx, event, data, env)
    }
    fn update(
        &mut self,
        child: &mut Label<AppState>,
        ctx: &mut UpdateCtx,
        old_data: &AppState,
        data: &AppState,
        env: &Env,
    ) {
        if data.show_hide == true && data.sidebar_view == 1 {
            child.set_text_color(Color::WHITE);
            ctx.request_layout();
        } else {
            child.set_text_color(Color::rgb8(170, 170, 170));
            ctx.request_layout();
        }
        child.update(ctx, old_data, data, env);
    }
}
fn main() {
    //窗口标题（使用 Unicode 字符）
    let window_title: &str = "Aimoss";
    //转换为宽字符字符串
    let wide_title: Vec<u16> = window_title.encode_utf16().chain(Some(0)).collect();
    //使用 FindWindowW 获取窗口句柄
    let hwnd: HWND = unsafe { FindWindowW(std::ptr::null(), wide_title.as_ptr()) };
    //判断程序实例是否已经打开,禁止多开
    if hwnd == std::ptr::null_mut() {
        let initial_state: AppState = AppState {
            display: "".to_string(),
            show_hide: true,
            current_view: 0,
            sidebar_view: 0,
            max_res_icon: "▢".to_string(),
            folder_path: "C:\\Users\\admin\\Desktop\\A股".to_string(),
            data: vec![5.82,5.97,5.82,5.86,5.65,5.72,5.69,5.7,5.72,5.61,5.39,5.42,5.32,5.64,5.67,5.65,5.63,]
            };
        let main_window: WindowDesc<AppState> = WindowDesc::new(ui_builder().controller(Windowstate{}))
            .title("Aimoss")
            .show_titlebar(false);
        AppLauncher::with_window(main_window)
            .delegate(Delegate)
            .configure_env(|env: &mut Env,_| {
                env.set(theme::WINDOW_BACKGROUND_COLOR, Color::rgb8(30, 30, 30));
            })
            .launch(initial_state)
            .expect("launch failed");
    } else {
        //恢复并激活窗口
        unsafe {
            ShowWindow(hwnd, SW_RESTORE);
            SetForegroundWindow(hwnd);
        };
    }
}
fn ui_builder() -> impl Widget<AppState> {
    let window: Split<AppState> = Split::columns(sidebar(), main_view())
        .draggable(true)
        .solid_bar(true)
        .split_point(0.1)
        .bar_size(0.0)
        .min_bar_area(0.1);
    let main_window: Either<AppState> = Either::new(
        |data: &AppState, _env: &Env| data.show_hide,
        window,
        main_view(),
    );
    let menu: druid::widget::ControllerHost<
        druid::widget::ControllerHost<
            druid::widget::Container<AppState>,
            druid::widget::Click<AppState>,
        >,
        MainMenuController,
    > = Label::new("☰")
        .with_text_size(17.)
        .align_vertical(UnitPoint::new(0.5, 0.3))
        .fix_size(30., 28.)
        .background(icon_painter())
        .on_click(|_, _, _| todo!())
        .controller(MainMenuController {});
    let titlebar: Flex<AppState> = Flex::column()
        .with_child(
            Flex::row()
                .with_child(menu)
                .with_flex_child(
                    Label::new("")
                        .center()
                        .controller(DragController {})
                        .expand_width(),
                    1.,
                )
                .with_child(
                    Label::new("一")
                        .with_text_size(13.)
                        .align_vertical(UnitPoint::new(0.5, 0.5))
                        .on_click(|ctx: &mut EventCtx, _data: &mut AppState, _env: &Env| {
                            ctx.window().clone().set_window_state(WindowState::Minimized)
                        })
                        .background(icon_painter())
                        .fix_size(30., 28.),
                )
                .with_child(Label::dynamic(|data:&AppState,&_|data.max_res_icon.clone())
                        .center()
                        .on_click(|ctx: &mut EventCtx, _data: &mut AppState, _env: &Env| {
                            if ctx.window().get_window_state() == WindowState::Restored {
                                ctx.window().clone().set_window_state(WindowState::Maximized);
                            } else {
                                ctx.window().clone().set_window_state(WindowState::Restored);
                            }
                        })
                        .background(icon_painter())
                        .fix_size(33., 28.)
                )
                .with_child(
                    Label::new("⨉")
                        .center()
                        .on_click(|ctx: &mut EventCtx, _data: &mut AppState, _env: &Env| {
                            ctx.submit_command(druid::commands::QUIT_APP)
                        })
                        .background(close_painter())
                        .fix_size(35., 28.),
                )
                .fix_height(28.)
                .background(Color::rgb8(25, 25, 25)),
        )
        .with_flex_child(main_window, 1.0);
    Flex::row()
        .with_child(toolbar())
        .with_flex_child(titlebar, 1.0)
}
// fn rainbow_painter() -> Painter<AppState> {
//     Painter::new(|ctx: &mut PaintCtx, _, _env: &Env| {
//         let bounds: druid::kurbo::RoundedRect = ctx.size().to_rect().to_rounded_rect(5.0);
// 	    let gradient: LinearGradient = LinearGradient::new(
//             UnitPoint::LEFT,
//             UnitPoint::RIGHT,
//             (Color::RED,Color::YELLOW,Color::GREEN,Color::BLUE,Color::NAVY,Color::PURPLE)//彩虹
//         );
//             ctx.fill(bounds, &gradient);
//         })
// }
// fn custom_button_painter()-> Painter<AppState>{
//     Painter::new(|ctx: &mut PaintCtx, _, _env: &Env| {
//         let bounds: druid::kurbo::RoundedRect = ctx.size().to_rect().to_rounded_rect(5.0);
//         ctx.fill(bounds, &Color::rgb8(50, 50, 50));
//         if ctx.is_hot() {
//             ctx.stroke(bounds, &Color::WHITE, 1.0);
//         }
//         if ctx.is_active() {
//             ctx.fill(bounds, &Color::rgb8(30, 30, 30));
//             ctx.stroke(bounds, &Color::WHITE, 1.0);
//         }
//     })
// }
fn close_painter() -> Painter<AppState> {
    Painter::new(|ctx: &mut PaintCtx, _, _env: &Env| {
        let bounds: druid::kurbo::RoundedRect = ctx.size().to_rect().to_rounded_rect(5.0);
        if ctx.is_hot() {
            ctx.fill(bounds, &Color::rgb8(255, 0, 0)); //红色
        }
    })
}
fn icon_painter() -> Painter<AppState> {
    Painter::new(|ctx: &mut PaintCtx, _, _env: &Env| {
        let bounds: druid::kurbo::RoundedRect = ctx.size().to_rect().to_rounded_rect(5.0);
        if ctx.is_hot() {
            ctx.fill(bounds, &Color::rgb8(65, 65, 65)); //亮灰色
        }
    })
}
fn toolbar() -> impl Widget<AppState> {
    let appicon: druid::widget::ControllerHost<druid::widget::SizedBox<AppState>, DragController> =
        Label::new("🐋")
            .with_text_size(17.)
            .with_text_color(Color::rgb8(17, 153, 221)) //vscode蓝/238,221,187VIP色
            .center()
            .fix_width(36.)
            .controller(DragController {});
    let folder: druid::widget::ControllerHost<
        druid::widget::SizedBox<AppState>,
        druid::widget::Click<AppState>,
    > = Label::new("📁")
        .with_text_size(17.)
        .with_text_color(Color::rgb8(170, 170, 170)) //灰色
        .controller(FolderIconColorController {})
        .center()
        .fix_width(36.)
        .on_click(
            move |_event: &mut EventCtx, data: &mut AppState, _env: &Env| {
                if data.sidebar_view != 0 {
                    data.sidebar_view = 0;
                    data.show_hide = true;
                } else {
                    data.show_hide = !data.show_hide
                }
            },
        );
    let document: druid::widget::ControllerHost<
        druid::widget::SizedBox<AppState>,
        druid::widget::Click<AppState>,
    > = Label::new("📄")
        .with_text_size(17.)
        .with_text_color(Color::rgb8(170, 170, 170)) //灰色
        .controller(DocumentIconColorController {})
        .center()
        .fix_width(36.)
        .on_click(
            move |_event: &mut EventCtx, data: &mut AppState, _env: &Env| {
                if data.sidebar_view != 1 {
                    data.sidebar_view = 1;
                    data.show_hide = true;
                } else {
                    data.show_hide = !data.show_hide
                }
            },
        );
    Flex::column()
        .main_axis_alignment(MainAxisAlignment::Start)
        .cross_axis_alignment(CrossAxisAlignment::Start)
        .with_child(appicon)
        .with_default_spacer()
        .with_child(folder)
        .with_default_spacer()
        .with_child(document)
        .with_default_spacer()
        .with_flex_child(
            Label::new("")
                .center()
                .controller(DragController {})
                .expand_height(),
            1.,
        )
        .with_flex_spacer(0.1) //是否居中显示控件
        .fix_width(36.0)
        .background(Color::rgb8(25, 25, 25))
}
fn primary_sidebar_painter() -> Painter<AppState> {
    Painter::new(|ctx: &mut PaintCtx, _, _env: &Env| {
        let bounds: druid::kurbo::RoundedRect = ctx.size().to_rect().to_rounded_rect(5.);
        ctx.fill(bounds, &Color::rgb8(45, 45, 45));
        if ctx.is_hot() {
            ctx.fill(bounds, &Color::rgb8(65, 65, 65)); //亮灰色
        }
        if ctx.is_active() {
            ctx.fill(bounds, &Color::rgb8(25, 25, 25));
        }
    })
}
fn primary_sidebar() -> impl Widget<AppState> {
    let switch: druid::widget::ControllerHost<
        druid::widget::SizedBox<AppState>,
        druid::widget::Click<AppState>,
    > = Label::new("NEXT🔜")
        .controller(SwitchViews {})
        .center()
        .background(primary_sidebar_painter())
        .fix_width(get_screen_width())
        .on_click(
            move |_event: &mut EventCtx, data: &mut AppState, _env: &Env| {
                if data.current_view == 0 {
                    data.current_view = 1;
                } else {
                    data.current_view = 0;
                }
            },
        );
    let ncpa: druid::widget::ControllerHost<
        druid::widget::SizedBox<AppState>,
        druid::widget::Click<AppState>,
    > = Label::new("网络连接")
        .center()
        .background(primary_sidebar_painter())
        .fix_width(get_screen_width())
        .on_click(|_ctx, _data, _env| {
            cmd::ncpa();
        });
    let stock_data: druid::widget::ControllerHost<
        druid::widget::ControllerHost<
            druid::widget::SizedBox<AppState>,
            druid::widget::Click<AppState>,
        >,
        MessageBoxTextController,
    > = Label::new("沪深京A股")
        .center()
        .background(primary_sidebar_painter())
        .fix_width(get_screen_width())
        .on_click(|_ctx: &mut EventCtx, data: &mut AppState, _env: &Env| {
            libloader::get_libfn!("reqwest.dll", "stock", stock_crawler, bool);
            let now: Instant = Instant::now();
            let rusult: bool = stock_crawler();
            let end: u128 = now.elapsed().as_millis();
            match rusult {
                true => data.display = format!(">>沪深京A股数据爬取成功-用时:{}毫秒", end),
                false => data.display = format!(">>发生错误:请检查网络连接-耗时:{}毫秒", end),
            }
        })
        .controller(MessageBoxTextController {});
    let control: druid::widget::ControllerHost<
        druid::widget::SizedBox<AppState>,
        druid::widget::Click<AppState>,
    > = Label::new("控制面板")
        .center()
        .background(primary_sidebar_painter())
        .fix_width(get_screen_width())
        .on_click(|_ctx, _data, _env| {
            cmd::control();
        });
    let new_excel: druid::widget::ControllerHost<
        druid::widget::SizedBox<AppState>,
        druid::widget::Click<AppState>,
    > = Label::new("新建Excel表")
        .center()
        .background(primary_sidebar_painter())
        .fix_width(get_screen_width())
        .on_click(|_ctx, _data, _env| {
            excel::new_excel();
        });
    let ssqiu_data: druid::widget::ControllerHost<
        druid::widget::SizedBox<AppState>,
        druid::widget::Click<AppState>,
    > = Label::new("双色球")
        .center()
        .background(primary_sidebar_painter())
        .fix_width(get_screen_width())
        .on_click(|_ctx: &mut EventCtx, data: &mut AppState, _env: &Env| {
            libloader::get_libfn!("reqwest.dll", "ssqiu", ssqiu_crawler, String);
            let rusult: String = ssqiu_crawler();
            data.display = rusult;
        });
    let merge: druid::widget::ControllerHost<druid::widget::SizedBox<AppState>, druid::widget::Click<AppState>> = Label::new("合并")
        .center()
        .background(primary_sidebar_painter())
        .fix_width(get_screen_width())
        .on_click(|_ctx: &mut EventCtx, data: &mut AppState, _env: &Env| {
            libloader::get_libfn!("merge.dll", "merge", merge,Result<u8, XlsxError>,folder_path:String);
            match merge(data.folder_path.clone()).unwrap() {
                1 => data.display = format!(">>合并完成文件已保存到:C:/Users/{}/Desktop/merged.xlsx",std::env::var_os("USERNAME").unwrap().into_string().unwrap()),
                _ => data.display = format!(">>No Excel files found in directory:{}",data.folder_path),
            }
        });
    Flex::column()
        .with_child(switch)
        .with_default_spacer()
        .with_child(ncpa)
        .with_default_spacer()
        .with_child(control)
        .with_default_spacer()
        .with_child(new_excel)
        .with_default_spacer()
        .with_child(stock_data)
        .with_default_spacer()
        .with_child(ssqiu_data)
        .with_default_spacer()
        .with_child(merge)
        .with_flex_spacer(1.)
        .border(Color::WHITE, 0.1)
}
fn associate_sidebar() -> impl Widget<AppState> {
    Flex::column()
        .with_child(Label::new("副侧栏"))
        .with_child(Label::new("一生二"))
        .with_child(Label::new("二生三"))
        .with_child(Label::new("三生万物"))
        .with_flex_spacer(1.)
        .border(Color::WHITE, 0.1)
}
fn sidebar() -> impl Widget<AppState> {
    ViewSwitcher::new(
        |data: &AppState, _env: &Env| data.sidebar_view,
        |selector: &u8, _data: &AppState, _env: &Env| match selector {
            0 => Box::new(primary_sidebar()),
            _ => Box::new(associate_sidebar()),
        },
    )
}
fn main_view() -> impl Widget<AppState> {
    let clear_button: druid::widget::ControllerHost<
        Button<AppState>,
        druid::widget::Click<AppState>,
    > = Button::new("清空").on_click(|_ctx: &mut EventCtx, data: &mut AppState, _env: &Env| {
        data.display.clear();
    });
    let clip_button: druid::widget::ControllerHost<
        Button<AppState>,
        druid::widget::Click<AppState>,
    > = Button::new("剪切").on_click(|_ctx: &mut EventCtx, data: &mut AppState, _env: &Env| {
        let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
        ctx.set_contents(data.display.to_owned()).unwrap();
        data.display.clear();
    });
    let copy_button: druid::widget::ControllerHost<
        Button<AppState>,
        druid::widget::Click<AppState>,
    > = Button::new("复制").on_click(|_ctx: &mut EventCtx, data: &mut AppState, _env: &Env| {
        let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
        ctx.set_contents(data.display.to_owned()).unwrap();
    });
    let paste_button: druid::widget::ControllerHost<
        Button<AppState>,
        druid::widget::Click<AppState>,
    > = Button::new("粘贴").on_click(|_ctx: &mut EventCtx, data: &mut AppState, _env: &Env| {
        let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
        let get_contents: String = ctx
            .get_contents()
            .unwrap_or(String::from("ERROR:粘贴内容非文本类型"));
        match data.display.is_empty() {
            true => data.display += &get_contents,
            false => data.display += &(String::from("\n") + &get_contents),
        }
    });
    let message_box: druid::widget::LensWrap<
        AppState,
        String,
        app_state_derived_lenses::display,
        druid::widget::SizedBox<String>,
    > = TextBox::multiline()
        .with_placeholder("文本显示框")
        .expand()
        .lens(AppState::display);
    let lower_right_widgets: druid::widget::Align<AppState> = Flex::column()
        .with_child(clear_button)
        .with_default_spacer()
        .with_child(clip_button)
        .with_default_spacer()
        .with_child(copy_button)
        .with_default_spacer()
        .with_child(paste_button)
        .align_horizontal(UnitPoint::new(0.5, 0.5));
    let lower_widgets: Flex<AppState> = Flex::row()
        .with_flex_child(message_box, 1.)
        .with_flex_child(lower_right_widgets, 0.1);
    let lower_widgets: EnvScope<AppState, Flex<AppState>> = EnvScope::new(
        |env: &mut Env, _data: &AppState| {
            env.set(theme::TEXTBOX_BORDER_WIDTH, 0.1);
            env.set(theme::BACKGROUND_LIGHT, Color::rgb8(25, 25, 25));
            env.set(theme::SCROLLBAR_COLOR, Color::rgb8(120, 120, 120))
        },
        lower_widgets,
    );
    let current_view: ViewSwitcher<AppState, u8> = ViewSwitcher::new(
        |data: &AppState, _env: &Env| data.current_view,
        |selector: &u8, _data: &AppState, _env: &Env| match selector {
            0 => Box::new(page_one()),
            _ => Box::new(line_chart()),
        },
    );
    Split::rows(current_view, lower_widgets)
        .draggable(true)
        .solid_bar(true)
        .split_point(0.7)//分割比例
        .bar_size(0.0)
        .min_bar_area(0.1)
        .controller(MessageBoxFocusController {})
}
impl AppDelegate<AppState> for Delegate {
     fn command(
        &mut self,
        _ctx: &mut DelegateCtx,
        _target: Target,
        cmd: &Command,
        data: &mut AppState,
        _env: &Env,
    ) -> Handled {
        if let Some(file_info) = cmd.get(commands::SAVE_FILE_AS) {
            if let Err(e) = std::fs::write(file_info.path(), &mut data.display[..]) {
                println!("Error writing file: {e}");
            }
            return Handled::Yes;
        }
        if let Some(file_info) = cmd.get(commands::OPEN_FILE) {
            data.folder_path = file_info.path().display().to_string();
            return Handled::Yes;
        }
        Handled::No
    }
}
fn make_main_menu() -> Menu<AppState> {
    let menu: Menu<AppState> = Menu::empty();
    //let mut menu_file: Menu<AppState> = Menu::new("File");
    let about: MenuItem<AppState> = MenuItem::new("关于").on_activate(
        move |_ctx: &mut druid::menu::MenuEventCtx<'_>, _data: &mut AppState, _env: &Env| {
            let window_title: &str = "Aimoss";
            let wide_title: Vec<u16> = window_title.encode_utf16().chain(Some(0)).collect();
            let hwnd: HWND = unsafe { FindWindowW(std::ptr::null(), wide_title.as_ptr()) };
            unsafe {
                // 调用 MessageBoxW 函数弹出消息框
                MessageBoxW(
                    hwnd, // 父窗口句柄，0 表示没有父窗口
                    "Version: 0.1.0
Date: 2024-5-30
Druid: 0.8.3
Language: Rust
OS: Windows11_x64
QQ: 3667636757
Phone: 17710721903"
                        .encode_utf16()
                        .chain(Some(0))
                        .collect::<Vec<u16>>()
                        .as_ptr(), // 消息内容
                    "Aimoss"
                        .encode_utf16()
                        .chain(Some(0))
                        .collect::<Vec<u16>>()
                        .as_ptr(), // 消息框标题
                    MB_OK | MB_ICONINFORMATION, // OK 按钮 + 信息图标
                );
            }
        },
    );
    menu.entry(about)
        .entry(druid::platform_menus::win::file::exit())
}
// 解析多个选中的文件路径
fn parse_multi_select_paths(buffer: &[u16]) -> Vec<String> {
    let mut paths: Vec<String> = vec![];
    let mut start: usize = 0;
    for i in 0..buffer.len() {
        if buffer[i] == 0 {
            if start == i {
                break;
            }
            let os_string: OsString = OsString::from_wide(&buffer[start..i]);
            paths.push(os_string.to_string_lossy().into_owned());
            start = i + 1;
        }
    }
    paths
}
fn select_file() -> Vec<String> {
    let mut file_buffer: Vec<u16> = vec![0u16; MAX_PATH as usize]; // 缓存260个空间来存储多个文件路径
    let mut ofn: OPENFILENAMEW = unsafe { std::mem::zeroed() };
    ofn.lStructSize = std::mem::size_of::<OPENFILENAMEW>() as u32;
    ofn.lpstrFile = file_buffer.as_mut_ptr();
    ofn.nMaxFile = file_buffer.len() as u32;
    let lpstr_filter: &str = "所有文件\0*.*\0文本文件\0*.TXT\0";
    let lpstr_filter: Vec<u16> = lpstr_filter.encode_utf16().chain(Some(0)).collect();
    ofn.lpstrFilter = lpstr_filter.as_ptr();
    ofn.nFilterIndex = 1;
    let lpstr_title: &str = "Select file";
    let lpstr_title: Vec<u16> = lpstr_title.encode_utf16().chain(Some(0)).collect();
    ofn.lpstrTitle = lpstr_title.as_ptr();
    ofn.Flags = OFN_ALLOWMULTISELECT | OFN_EXPLORER;
    if unsafe { GetOpenFileNameW(&mut ofn) } != 0 {
        parse_multi_select_paths(&file_buffer) // 成功选择文件
    } else {
        vec!["No files were selected or an error occurred.".to_string()]
    }
}
fn page_one() -> impl Widget<AppState> {
    let rs: FileSpec = FileSpec::new("Rust", &["rs"]);
    let txt: FileSpec = FileSpec::new("Text", &["txt"]);
    // The options can also be generated at runtime,so to show that off we create a String for the default save name.
    let save_dialog_options: FileDialogOptions = FileDialogOptions::new()
        .allowed_types(vec![rs, txt])
        .default_type(txt);
    let save: druid::widget::ControllerHost<Button<AppState>, druid::widget::Click<AppState>> =
        Button::new("Save").on_click(move |ctx: &mut EventCtx<'_, '_>, _, _| {
            ctx.submit_command(druid::commands::SHOW_SAVE_PANEL.with(save_dialog_options.clone()))
        });
    let open: druid::widget::ControllerHost<Button<AppState>, druid::widget::Click<AppState>> =
        Button::new("Open").on_click(|_ctx: &mut EventCtx, data: &mut AppState, _env: &Env| {
            let path: Vec<String> = select_file();
            if path.len() == 1 {
                match std::fs::read_to_string(path[0].as_str()) {
                    Ok(s) => {
                        data.display = s.to_string();
                    }
                    Err(e) => {
                        println!("Error opening file: {e}");
                    }
                }
            } else {
                data.display = "由于选择了多个文件待后续代码处理......".to_string();
            }
        });
    let label: druid::widget::Padding<AppState, Label<AppState>> = Label::dynamic(|data: &AppState, _env: &Env| {
            if data.folder_path.is_empty() {
                "未选择文件夹".to_string()
            } else {
                format!("已选择文件夹: {}", data.folder_path)
            }
        })
        .with_text_size(16.0)
        .padding(5.0);

    let button = Button::new("文件夹")
        .on_click(|ctx, _data: &mut AppState, _env| {
            let options: FileDialogOptions = FileDialogOptions::new()
                .select_directories()
                .title("选择文件夹")
                .button_text("选择");
            ctx.submit_command(druid::commands::SHOW_OPEN_PANEL.with(options));
        })
        .padding(5.0);        
    let mut row: Flex<AppState> = Flex::column();
    row.add_child(save);
    row.add_child(open);
    row.add_child(label);
    row.add_child(button);
    Align::centered(row)
}
fn line_chart() -> Painter<AppState> {
    Painter::new(|ctx: &mut PaintCtx<'_, '_, '_>, data: &AppState, env: &Env| {
        // 获取绘制区域的边界
        let size: Size = ctx.size();
        let width: f64 = size.width;
        let height: f64 = size.height;
        // 获取数据
        let data: &Vec<f64> = &data.data;
        // 将数据转换为屏幕坐标
        let max_value: f64 = *data.iter().max_by(|a: &&f64, b: &&f64| a.partial_cmp(b).unwrap()).unwrap()+10.;
        let step_x: f64 = width / (data.len() as f64 + 1.0); // X轴步长
        let points: Vec<Point> = data.iter().enumerate().map(|(i, &y)| {
            let x: f64 = (i as f64 + 1.0) * step_x; // X轴原点坐标
            let y: f64 = height - (y / max_value * height); // Y轴原点坐标
            Point::new(x, y)
        }).collect();
        ctx.stroke(Line::new(points[0], (points[points.len()-1].x,points[0].y)), &Color::rgb8(255, 0, 255), 2.0);//X轴
        ctx.stroke(Line::new((points[points.len()-1].x,points[0].y), (points[points.len()-1].x-15.,points[0].y+10.)), &Color::rgb8(255, 0, 255), 2.0);//X轴箭头1
        ctx.stroke(Line::new((points[points.len()-1].x,points[0].y), (points[points.len()-1].x-15.,points[0].y-10.)), &Color::rgb8(255, 0, 255), 2.0);//X轴箭头2
        ctx.stroke(Line::new(points[0], (points[0].x,20.)), &Color::rgb8(255, 0, 255), 2.0);//Y轴
        ctx.stroke(Line::new((points[0].x,20.), (points[0].x-10.,35.)), &Color::rgb8(255, 0, 255), 2.0);//Y轴箭头1
        ctx.stroke(Line::new((points[0].x,20.), (points[0].x+10.,35.)), &Color::rgb8(255, 0, 255), 2.0);//Y轴箭头2
        // 绘制折线
        for i in 1..points.len() {
            ctx.stroke(Line::new(points[i-1], points[i]), &Color::rgb8(255, 0, 0), 2.0);
        }
        // 在每个节点上绘制Y坐标
        for (i, &point) in points.iter().enumerate() {
            let mut layout: TextLayout<String> = TextLayout::<String>::from_text(&data[i].to_string());
            layout.set_font(FontDescriptor::new(FontFamily::SERIF).with_size(15.0));
            layout.set_text_color(Color::rgb8(255, 255, 255));
            layout.rebuild_if_needed(ctx.text(), env);
            let text_size: Size = layout.size();
            let x: f64 = point.x - text_size.width / 2.0;
            let y: f64 = point.y - text_size.height - 5.0; // Y坐标上方
            layout.draw(ctx, Point::new(x, y));
        }
        //左上角显示指数
        let mut layout: TextLayout<String> = TextLayout::<String>::from_text("岩山科技 002195 (2025年5月9号-至今)");
            layout.set_font(FontDescriptor::new(FontFamily::SERIF).with_size(20.0));
            layout.set_text_color(Color::rgb8(255, 0, 0));
            layout.rebuild_if_needed(ctx.text(), env);
            let x: f64 = points[0].x+15.;
            let y: f64 = 45.;
            layout.draw(ctx, Point::new(x, y));
    })
}